/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Gestores;

import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 *
 * @author radxt
 */
public class XMLCrear {

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder;
    Document doc;
    Element rootElement;

    public XMLCrear(String raiz) {
        try {
            this.docBuilder = this.docFactory.newDocumentBuilder();
             this.doc = docBuilder.newDocument();
            
           this.rootElement  = this.doc.createElement(raiz);
            this.doc.appendChild(rootElement);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(XMLCrear.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void nuevoUser(String code, String password, String grupo, String login, String nombre) {
        Element User = doc.createElement("Usuario");
        rootElement.appendChild(User);

        Attr attr = doc.createAttribute("id");
        attr.setValue(code);
        User.setAttributeNode(attr);

        Attr attr1 = doc.createAttribute("pass");
        attr1.setValue(password);
        User.setAttributeNode(attr1);
        
        Attr attr2 = doc.createAttribute("grupo");
        attr2.setValue(grupo);
        User.setAttributeNode(attr2);
        
        Attr attr3 = doc.createAttribute("login");
        attr3.setValue(login);
        User.setAttributeNode(attr3);
        
        Attr attr4 = doc.createAttribute("nombre");
        attr4.setValue(nombre);
        User.setAttributeNode(attr4);
    }

    public void salvarXML(String path) {
        try {
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File(path));
            transformer.transform(source, result);
        } catch (TransformerConfigurationException ex) {
            Logger.getLogger(XMLCrear.class.getName()).log(Level.SEVERE, null, ex);
        } catch (TransformerException ex) {
            Logger.getLogger(XMLCrear.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
